package com.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.model.Article;
import com.model.Question;
import com.search.SearchService;
import com.service.ArticleService;
import com.service.QuestionService;

@Component
@Aspect
public class SearchAOP {

	@Autowired
	private SearchService searchService;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private QuestionService questionService;

	// __________________________________________Article______________________________________________

	@AfterReturning(value = "execution(public * com.service.impl.ArticleServiceImpl.addArticle(..))", returning = "reVal")
	public void afterAddArticle(JoinPoint jp, Object reVal) {
		searchService.updateArticleIndex((Article) reVal);
	}

	@AfterReturning(value = "execution(public * com.service.impl.ArticleServiceImpl.addArticleTag(..))", returning = "articleId")
	public void afterAddArticleTag(JoinPoint jp, int articleId) {
		if (articleId != 0) {
			Article article = articleService.findArticleById(articleId);
			if (article != null)
				searchService.updateArticleIndex(article);
		}
	}

	@AfterReturning(value = "execution(public * com.service.impl.ArticleServiceImpl.deleteArticle(..))", returning = "articleId")
	public void afterDeleteArticle(JoinPoint jp, int articleId) {
		searchService.delete(articleId, "article");
	}

	// __________________________________________Question______________________________________________

	@AfterReturning(value = "execution(public * com.service.impl.QuestionServiceImpl.answerQuestion(..))", returning = "reVal")
	public void afterAnswerQuestion(JoinPoint jp, Object reVal) {
		searchService.updateQuestionIndex((Question) reVal);
	}

	@AfterReturning(value = "execution(public * com.service.impl.QuestionServiceImpl.addQuestionTag(..))", returning = "questionId")
	public void afterAddQuestionTag(JoinPoint jp, int questionId) {
		if (questionId != 0) {
			Question question = questionService.findById(questionId);
			if (question != null && question.getIsAnswered() == 1)
				searchService.updateQuestionIndex(question);
		}
	}

	@AfterReturning(value = "execution(public * com.service.impl.QuestionServiceImpl.deleteQuestion(..))", returning = "questionId")
	public void afterAddAnswerQuestion(JoinPoint jp, int questionId) {
		searchService.delete(questionId, "question");
	}
}
